﻿using System;
using System.Dynamic;

namespace Api.Sales.Orders.Messages.Payment
{
    public class MeihuaPay
    {
        private static readonly Lazy<MeihuaPay> lazy =
           new Lazy<MeihuaPay>(() => new MeihuaPay());
        public static MeihuaPay Instance { get { return lazy.Value; } }

        internal void GeneratePaymentInfo(dynamic request, dynamic response)
        {
            string paymentNumber = request.vifudjhk;
            string paymentDate = request.igjcuijm;
            if (string.IsNullOrWhiteSpace(paymentNumber))
                request.vifudjhk = paymentNumber = NewPaymentNumber(paymentDate);

            dynamic payment = GeneratePayment(paymentNumber);
            response.payment = payment;
        }

        dynamic GeneratePayment(string number)
        {
            dynamic payment = new ExpandoObject();
            payment.company = "MEIHUA";
            payment.number_list = new ExpandoObject();
            payment.number_list.number = new[] {
                number
            };

            return payment;
        }

        private string GenerateLongGuid()
        {
            byte[] buffer = Guid.NewGuid().ToByteArray();
            return BitConverter.ToInt64(buffer, 0).ToString();
        }

        private string NewPaymentNumber(string baseDateTime = "")
        {
            DateTime baseDate;
            if (!DateTime.TryParse(baseDateTime, out baseDate))
                baseDate = DateTime.Now;

            string dateId = baseDate.ToString("yyyyMMddHH");
            string random = GenerateLongGuid().Substring(1);
            return dateId + random;
        }
    }
}